package com.atguigu.guliedu.edu.service.impl;

import com.atguigu.guliedu.edu.entity.Subject;
import com.atguigu.guliedu.edu.entity.vo.SubjectVo;
import com.atguigu.guliedu.edu.mapper.SubjectMapper;
import com.atguigu.guliedu.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author java
 * @since 2021-02-01
 */
@Service
@Slf4j
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public List<SubjectVo> tree() {
        //获取所有数据
        List<Subject> list = baseMapper.selectList(null);
        //遍历封装成树形结构的数据

        List<SubjectVo> listVo = list.stream().map(subject -> {
            SubjectVo subjectVo = new SubjectVo();
            BeanUtils.copyProperties(subject, subjectVo);
            return subjectVo;
        }).collect(Collectors.toList());

        List<SubjectVo> collect = listVo.stream().filter(level1 -> {
            //查找父级分类
            return level1.getParentId().equals("0");
        }).map(level1 -> {
            level1.setChildren(getSubjectChildren(level1, listVo));
            return level1;
        }).collect(Collectors.toList());
        return collect;

    }

    public List<SubjectVo> getSubjectChildren(SubjectVo level1, List<SubjectVo> list) {
        List<SubjectVo> collect = list.stream().filter(subject -> {
            return level1.getId().equals(subject.getParentId());
        }).collect(Collectors.toList());

        return collect;
    }


}
